package com.ml.mall.service.state.impl;

import com.ml.mall.consts.OrderStateConsts;
import com.ml.mall.consts.SupplierOrderStateConsts;
import com.ml.mall.entity.state.SysOrderState;
import com.ml.mall.entity.supplier.SysOrderSupplier;
import com.ml.mall.mapper.order.SysOrderMapper;
import com.ml.mall.mapper.state.SysOrderStateMapper;
import com.ml.mall.mapper.supplier.SysOrderSupplierMapper;
import com.ml.mall.service.state.SysOrderStateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* <p>
    *  服务实现类
    * </p>
*
* @author kyyang
* Created 2021-05-24
*/
@Service
@Slf4j
public class SysOrderStateServiceImpl extends ServiceImpl<SysOrderStateMapper, SysOrderState> implements SysOrderStateService {

    @Autowired
    private  SysOrderStateMapper  sysOrderStateMapper;

    @Autowired
    private SysOrderSupplierMapper sysOrderSupplierMapper;

    @Autowired
    private SysOrderMapper sysOrderMapper;

    @Override
    @Async
    public void createOrderState(String soid, Integer state,Long oid) {
            SysOrderState sysOrderState=new SysOrderState();
            sysOrderState.setStateChageAt(new Date());
            sysOrderState.setState(state);
            sysOrderState.setOid(soid);
            sysOrderStateMapper.insert(sysOrderState);
            if(state.equals(SupplierOrderStateConsts.ORDER_STATE_COMPLETE)){
                checkAllSupplierState(oid);
            }
    }

    //检验当前订单是否全部完成；完成则更新大的订单状态为完成
    private void checkAllSupplierState(Long oid){
        List<SysOrderSupplier> sysOrderSuppliers = sysOrderSupplierMapper.selectSordByOid(oid);
        Boolean isAllCompele = true;
        for(SysOrderSupplier sord:sysOrderSuppliers){
            if(!sord.getState().equals(SupplierOrderStateConsts.ORDER_STATE_COMPLETE)){
                log.info("sord====={}",sord);
                isAllCompele = false;
            }
        }
        //如果都是完成的更新大订单为完成
        if(isAllCompele){
            sysOrderMapper.updateOrderState(oid,OrderStateConsts.ORDER_STATE_COMPLETE);
        }
    }
}
